<template>
  <view class="community-container">
    <!-- 顶部操作栏 -->
    <view class="action-bar">
      <view class="filter-options">
        <view class="filter-item" :class="{ active: activeFilter === 'all' }" @click="setFilter('all')">
          <text class="filter-text">全部</text>
          <view class="filter-line" v-if="activeFilter === 'all'"></view>
        </view>
        <view class="filter-item" :class="{ active: activeFilter === 'liked' }" @click="setFilter('liked')">
          <text class="filter-text">已点赞</text>
          <view class="filter-line" v-if="activeFilter === 'liked'"></view>
        </view>
      </view>
      <view class="post-btn" @click="navigateToEdit">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
          <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
        </svg>
        <text>发布</text>
      </view>
    </view>
    
    <!-- 帖子列表 -->
    <scroll-view scroll-y class="post-list" @scrolltolower="loadMorePosts" refresher-enabled @refresherrefresh="refreshPosts" :refresher-triggered="isRefreshing">
      <view v-if="filteredPosts.length === 0" class="empty-posts">
        <image src="/static/images/empty-posts.png" class="empty-image"></image>
        <text class="empty-text">暂无帖子，去发布一条吧</text>
        <button class="create-post-btn" @click="navigateToEdit">发布帖子</button>
      </view>
      
      <view v-else class="posts-container">
        <view class="post-item" v-for="post in filteredPosts" :key="post.id" @click="navigateToDetail(post.id)">
          <view class="post-header">
            <view class="post-user-info">
              <image class="post-avatar" :src="post.avatar || '/static/images/default-avatar.png'"></image>
              <view class="post-user-name-time">
                <text class="post-username">{{ post.username || '我' }}</text>
                <text class="post-time">{{ formatTime(post.createdAt) }}</text>
              </view>
            </view>
            <view class="post-more">
              <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="12" cy="12" r="1"></circle>
                <circle cx="19" cy="12" r="1"></circle>
                <circle cx="5" cy="12" r="1"></circle>
              </svg>
            </view>
          </view>
          
          <view class="post-content">
            <view class="post-title">{{ post.title }}</view>
            <view class="post-text">{{ truncateText(post.content) }}</view>
          </view>
          
          <view class="post-images" v-if="post.images && post.images.length">
            <view class="image-grid" :class="'grid-' + Math.min(post.images.length, 3)">
              <image 
                v-for="(img, index) in post.images.slice(0, 3)" 
                :key="index" 
                :src="img" 
                class="post-image" 
                mode="aspectFill"
              ></image>
            </view>
          </view>
          
          <view class="post-actions">
            <view class="action-item" @click.stop="toggleLike(post.id)">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" :style="post.isLiked ? 'fill: #ff5151; stroke: #ff5151' : ''">
                <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
              </svg>
              <text class="action-count">{{ post.likes }}</text>
            </view>
            <view class="action-item">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path>
              </svg>
              <text class="action-count">{{ post.comments ? post.comments.length : 0 }}</text>
            </view>
            <view class="action-item" @click.stop="sharePost(post)">
              <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="18" cy="5" r="3"></circle>
                <circle cx="6" cy="12" r="3"></circle>
                <circle cx="18" cy="19" r="3"></circle>
                <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line>
                <line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line>
              </svg>
              <text class="action-count">分享</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="loading-more" v-if="isLoading && filteredPosts.length > 0">
        <text class="loading-text">加载中...</text>
      </view>
    </scroll-view>
    
    <!-- 发布按钮 -->
    <view class="publish-btn" @click="navigateToEdit">
      <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <line x1="12" y1="5" x2="12" y2="19"></line>
        <line x1="5" y1="12" x2="19" y2="12"></line>
      </svg>
    </view>
  </view>
</template>

<script>
import { usePostStore } from '@/store/postStore';
import { storeToRefs } from 'pinia';
import { generalIcons } from '@/static/icons/icon-svg';

export default {
  setup() {
    const postStore = usePostStore();
    const { posts } = storeToRefs(postStore);
    
    return {
      postStore,
      posts
    };
  },
  
  data() {
    return {
      activeFilter: 'all',
      isLoading: false,
      isRefreshing: false,
      generalIcons: generalIcons,
      isNavigating: false
    };
  },
  
  computed: {
    filteredPosts() {
      if (this.activeFilter === 'all') {
        return this.posts;
      } else if (this.activeFilter === 'liked') {
        return this.posts.filter(post => post.isLiked);
      }
      return this.posts;
    }
  },
  
  onLoad() {
    this.postStore.loadPostsFromStorage();
    // 初始化示例帖子
    this.postStore.initSamplePosts();
    
    // 监听刷新事件
    uni.$on('refreshCommunity', this.handleRefresh);
  },
  
  onUnload() {
    // 卸载事件监听
    uni.$off('refreshCommunity', this.handleRefresh);
  },
  
  methods: {
    // 新增刷新处理方法
    handleRefresh() {
      console.log('收到刷新社区页面事件');
      this.refreshPosts();
    },
    
    setFilter(filter) {
      this.activeFilter = filter;
    },
    
    navigateToEdit(postId) {
      if (this.isNavigating) {
        console.log('防止重复点击，忽略本次操作');
        return;
      }
      
      console.log('准备跳转到帖子编辑页面');
      this.isNavigating = true;
      
      try {
        setTimeout(() => {
          uni.navigateTo({
            url: postId ? `/pages/post/edit?id=${postId}` : '/pages/post/edit',
            success: () => {
              console.log('成功跳转到编辑页面');
            },
            fail: (err) => {
              console.error('跳转失败:', err);
              
              setTimeout(() => {
                uni.redirectTo({
                  url: '/pages/post/edit',
                  fail: (redirectErr) => {
                    console.error('重定向也失败:', redirectErr);
                    
                    uni.showToast({
                      title: '页面跳转失败，请重试',
                      icon: 'none',
                      duration: 2000
                    });
                  }
                });
              }, 300);
            },
            complete: () => {
              setTimeout(() => {
                this.isNavigating = false;
              }, 200);
            }
          });
        }, 300);
      } catch (error) {
        console.error('导航方法执行错误:', error);
        uni.showToast({
          title: '系统错误，请重试',
          icon: 'none'
        });
        setTimeout(() => {
          this.isNavigating = false;
        }, 20000);
      }
    },
    
    navigateToDetail(postId) {
      uni.navigateTo({
        url: `/pages/post/detail?id=${postId}`
      });
    },
    
    toggleLike(postId) {
      this.postStore.toggleLike(postId);
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      
      // 小于1分钟
      if (diff < 60 * 1000) {
        return '刚刚';
      }
      
      // 小于1小时
      if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`;
      }
      
      // 小于24小时
      if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
      }
      
      // 小于7天
      if (diff < 7 * 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
      }
      
      // 大于7天
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    },
    
    truncateText(text) {
      if (!text) return '';
      return text.length > 100 ? text.substring(0, 100) + '...' : text;
    },
    
    sharePost(post) {
      uni.showShareMenu({
        withShareTicket: true
      });
    },
    
    loadMorePosts() {
      if (this.isLoading) return;
      
      this.isLoading = true;
      
      // 模拟加载更多数据
      setTimeout(() => {
        this.isLoading = false;
      }, 1000);
    },
    
    refreshPosts() {
      this.isRefreshing = true;
      
      try {
        console.log('刷新帖子列表');
        // 从存储重新加载数据
        this.postStore.loadPostsFromStorage();
        
        setTimeout(() => {
          console.log('刷新完成，当前帖子数量:', this.posts.length);
          this.isRefreshing = false;
          
          uni.showToast({
            title: '刷新成功',
            icon: 'success',
            duration: 1000
          });
        }, 500);
      } catch (error) {
        console.error('刷新帖子列表错误:', error);
        this.isRefreshing = false;
        
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      }
    },
    
    loadPostData() {
      try {
        const postStore = usePostStore();
        const post = postStore.getPostById(this.postId);
        
        if (post) {
          this.postForm = {
            title: post.title || '',
            content: post.content || '',
            images: post.images || [],
            tags: post.tags || [],
            location: post.location || ''
          };
        } else {
          console.log('找不到帖子');
          this.postForm = {
            title: '',
            content: '',
            images: [],
            tags: [],
            location: ''
          };
        }
      } catch (error) {
        console.error('加载帖子数据错误:', error);
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style>
.community-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 100rpx;
  position: relative;
}

/* 顶部操作栏样式 */
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #ffffff, #f8fafc);
  box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 10;
}

.filter-options {
  display: flex;
  gap: 30rpx;
}

.filter-item {
  position: relative;
  padding: 10rpx 10rpx;
  transition: all 0.3s;
}

.filter-text {
  font-size: 32rpx;
  color: #333;
  font-weight: normal;
}

.filter-item.active .filter-text {
  color: #3F7BFC;
  font-weight: 500;
}

.filter-line {
  position: absolute;
  bottom: -5rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background-color: #3F7BFC;
  border-radius: 3rpx;
}

.post-btn {
  display: flex;
  align-items: center;
  gap: 10rpx;
  color: #3F7BFC;
  font-size: 28rpx;
  font-weight: 500;
}

.post-btn svg {
  width: 40rpx;
  height: 40rpx;
  stroke: #3F7BFC;
}

/* 帖子列表样式 */
.post-list {
  height: calc(100vh - 90rpx);
  box-sizing: border-box;
}

.posts-container {
  padding: 20rpx;
}

.post-item {
  margin-bottom: 24rpx;
  border-radius: 16rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  padding: 30rpx;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.post-user-info {
  display: flex;
  align-items: center;
}

.post-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  background-color: #eee;
}

.post-user-name-time {
  display: flex;
  flex-direction: column;
}

.post-username {
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 4rpx;
  color: #333;
}

.post-time {
  font-size: 24rpx;
  color: #999;
}

.post-more {
  color: #999;
  padding: 10rpx;
}

.post-content {
  margin-bottom: 20rpx;
}

.post-title {
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 12rpx;
  color: #333;
}

.post-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20rpx;
}

.post-images {
  margin-bottom: 20rpx;
}

.image-grid {
  display: grid;
  grid-gap: 10rpx;
  border-radius: 10rpx;
  overflow: hidden;
}

.grid-1 {
  grid-template-columns: 1fr;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
}

.grid-3 {
  grid-template-columns: 1fr 1fr 1fr;
}

.post-image {
  width: 100%;
  height: 200rpx;
  background-color: #f5f5f5;
  object-fit: cover;
}

.post-actions {
  display: flex;
  justify-content: space-between;
  padding-top: 20rpx;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
}

.action-item {
  display: flex;
  align-items: center;
  gap: 10rpx;
  color: #666;
}

.action-count {
  font-size: 26rpx;
}

/* 发布按钮样式 */
.publish-btn {
  position: fixed;
  right: 30rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(63, 123, 252, 0.3);
  z-index: 100;
  color: white;
}

.publish-btn svg {
  stroke: white;
}

/* 空状态样式 */
.empty-posts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.create-post-btn {
  background: linear-gradient(135deg, #4B89FD, #3F7BFC);
  color: white;
  padding: 20rpx 60rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
}

/* 加载更多样式 */
.loading-more {
  text-align: center;
  padding: 30rpx 0;
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}
</style> 